<template>
	<view class="share">
		<g-navbar title="分享" :isShowBack="version == VERSION_TYPE.OFFICAL_VERSION" backgroundColor="none" />
		<view class="share-main" :style="{'backgroundImage':`url(${pagePosterUrl})`}">
			<view class="poster-wrapper" :style="{'height':posterPageHeight+'px'}">
				<image :src="pagePosterUrl" style="width: 100%;height: 100%;" mode="heightFix" />
			</view>
			<image v-if="qrcodeUrl" :src="qrcodeUrl" class="qrcode" :style="{'top':qrcodePageTop+'px'}"></image>
			<view class="button-wrapper" v-if="isBtnShow">
				<g-button :width="686" :height="104" btn_text="保存到相册" @click="clickBtn"></g-button>
			</view>
		</view>
		<canvas id="qrcode" canvas-id="qrcode" class="qrcode-canvas"></canvas>
		<canvas id="poster" canvas-id="poster" v-if="posterWidth&&posterHeight"
			:style="{'width':`${posterWidth}px`,'height':`${posterHeight}px`}" class="poster"></canvas>
		<selectPoster ref="selectPosterRef" :completePosterList="completePosterList" />
		<g-tabbar v-show="version === VERSION_TYPE.EXP_VERSION" />
	</view>
</template>

<script lang="ts" setup>
	// import UQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
	import { onShow, onHide, onLoad } from '@dcloudio/uni-app';
	import selectPoster from './components/selectPoster/selectPoster';
	import { ref, Ref, reactive, onMounted, computed, watch } from 'vue';
	import { useUserData } from '@/hooks/useUserData';
	import REST_URL from '@/http/http.restUrl';
	import { useStore } from 'vuex';
	import interceptor from '@/router/router.interceptor';
	import { VERSION_TYPE } from '@/enum/version';
	import { GET_STORE_USERINFO } from '@/store/gettersType';

	interface IPoster {
		images : string;
		x_location : string;
		y_location : string;
		poster_length : string;
		poster_width : string;
		qrcode_length : string;
		qrcode_width : string;
	}

	//海报列表
	const posterList : Ref<IPoster[]> = ref([]);
	//二维码链接
	const qrcodeUrl : Ref<string> = ref('');

	//海报的宽
	const posterWidth : Ref<number> = ref(0);
	//海报的高
	const posterHeight : Ref<number> = ref(0);

	//海报在页面上的高
	const posterPageHeight : Ref<number> = ref(0);

	//二维码在页面的TOP
	const qrcodePageTop : Ref<number> = ref(0);

	//页面海报
	const pagePosterUrl : Ref<string> = ref('');


	//二维码图片
	let qrcodeImg : Ref<string> = ref('');
	//完整海报图列表
	let completePosterList : Ref<string[]> = ref([]);

	const isBtnShow : Ref<boolean> = ref(false);

	const selectPosterRef : Ref<any> = ref(null);


	const store = useStore();

	async function getPosterList() : Promise<void> {
		const { data } = await uni.http.POST(REST_URL.getPosterList, {
			customer_id: store.getters[GET_STORE_USERINFO].id,
			versions: 1,
			// redirect_url: store.state.version == 2 ? '/pages_login/register/register' : '',
		})

		console.log('海报==>', data)
		// qrcodeUrl.value = store.state.version == 2 ? data.redirect_url : data.qrcodeUrl;
		qrcodeUrl.value = data.qrcodeUrl;
		posterList.value = data.background;

		posterWidth.value = Number(posterList.value[0].poster_width);
		posterHeight.value = Number(posterList.value[0].poster_length);
		// console.log((uni.getWindowInfo().s/Number(posterList.value[0].poster_width))
		posterPageHeight.value = Number((uni.getWindowInfo().screenWidth / Number(posterList.value[0].poster_width)) * Number(posterList.value[0].poster_length));
		console.log('posterPageHeight=========>', posterPageHeight.value)
		qrcodePageTop.value = Number((uni.getWindowInfo().screenWidth / Number(posterList.value[0].poster_width)) * Number(posterList.value[0].y_location));
		pagePosterUrl.value = posterList.value[0].images;
	}

	onLoad(() => {
		interceptor.beforeEach({ url: '/pages/share/share' })
	})


	onShow(async () => {
		await uni.loginManger.$interceptor;
		if (!qrcodeUrl.value || !posterList.value.length) {
			await getPosterList();
		}
		if (!completePosterList.value.length) {
			uni.showLoading({
				title: '正在生成海报'
			})
			//二维码图片
			qrcodeImg.value = await drawQRCode2(qrcodeUrl.value);
			console.log(qrcodeImg.value)
			//绘制海报
			completePosterList.value = await drawCompletePoster(posterList.value, qrcodeImg.value);
			isBtnShow.value = true;
			uni.hideLoading();
		}
	})

	onHide(() => {
		console.log('onHide')
		uni.hideLoading();
	})




	//生成二维码图片
	// function drawQRCode(qrcodeUrl : string) : Promise<string> {
	// 	return new Promise((resolve, reject) => {
	// 		try {
	// 			// 获取uQRCode实例
	// 			var qr = new UQRCode();
	// 			// 设置二维码内容
	// 			qr.data = qrcodeUrl;
	// 			// 设置二维码大小，必须与canvas设置的宽高一致
	// 			qr.size = uni.getWindowInfo().screenWidth * 284 / 750;
	// 			// 调用制作二维码方法
	// 			qr.make();
	// 			// 获取canvas上下文
	// 			var canvasContext = uni.createCanvasContext('qrcode'); // 如果是组件，this必须传入
	// 			// 设置uQRCode实例的canvas上下文
	// 			qr.canvasContext = canvasContext;
	// 			// 调用绘制方法将二维码图案绘制到canvas上
	// 			qr.drawCanvas();

	// 			uni.canvasToTempFilePath({
	// 				canvasId: 'qrcode',
	// 				success: (res) => {
	// 					resolve(res.tempFilePath)
	// 				},
	// 				fail: () => {
	// 					reject();
	// 				}
	// 			})
	// 		} catch (e) {
	// 			reject();
	// 		}
	// 	})
	// }


	function drawQRCode2(qrcodeUrl : string) : Promise<string> {
		return new Promise((resolve, reject) => {
			try {
				uni.getImageInfo({
					src: qrcodeUrl,
					success: async (res) => {
						const ctx = uni.createCanvasContext("qrcode");
						ctx.beginPath();
						ctx.fillStyle = '#ffffff';
						ctx.fillRect(0, 0, uni.getWindowInfo().screenWidth * 284 / 750, uni.getWindowInfo().screenWidth * 284 / 750);
						// #ifdef MP-WEIXIN
						ctx.drawImage(res.path, 0, 0, uni.getWindowInfo().screenWidth * 284 / 750, uni.getWindowInfo().screenWidth * 284 / 750);
						// #endif
						// #ifdef H5
						ctx.drawImage(await getBase64(res.path), 0, 0, uni.getWindowInfo().screenWidth * 284 / 750, uni.getWindowInfo().screenWidth * 284 / 750);
						// #endif
						ctx.closePath();
						ctx.draw(false, (e) => {
							uni.canvasToTempFilePath({
								canvasId: 'qrcode',
								success: (res) => {
									ctx.clearRect(0, 0, uni.getWindowInfo().screenWidth * 284 / 750, uni.getWindowInfo().screenWidth * 284 / 750);
									resolve(res.tempFilePath)
								},
								fail: () => {
									console.log('fail')
									reject()
								}
							});
						})
					},
					fail: () => {
						reject()
					}
				})
			} catch (e) {

			}
		})
	}


	//生成完整海报
	function drawCompletePoster(posterList : IPoster[], qrcodeImg : string) : Promise<string[]> {
		return new Promise(async (resolve, reject) => {
			const list : string[] = [];
			try {
				for (let i = 0; i < posterList.length; i++) {
					const posterItem = await drawPosterItem(posterList[i], qrcodeImg);
					list.push(posterItem)
				}
				resolve(list);
			} catch (e) {
				console.log(e)
				reject()
			}
		})
	}

	function drawPosterItem(poster : IPoster, qrcodeImg : string) : Promise<string> {
		return new Promise((resolve, reject) => {
			try {
				uni.getImageInfo({
					src: poster.images,
					success: async (res) => {
						const ctx = uni.createCanvasContext("poster");
						ctx.beginPath();
						ctx.fillStyle = '#ffffff';
						ctx.fillRect(0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #ifdef MP-WEIXIN
						ctx.drawImage(res.path, 0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #endif
						// #ifdef H5
						ctx.drawImage(await getBase64(poster.images), 0, 0, Number(poster.poster_width), Number(poster.poster_length));
						// #endif
						ctx.drawImage(qrcodeImg, Number(poster.x_location), Number(poster.y_location), Number(poster.qrcode_width), Number(poster.qrcode_length));
						ctx.closePath();

						ctx.draw(false, (e) => {
							uni.canvasToTempFilePath({
								canvasId: 'poster',
								success: (res) => {
									ctx.clearRect(0, 0, Number(poster.poster_width), Number(poster.poster_length));
									resolve(res.tempFilePath)
								},
								fail: () => {
									console.log('fail')
									reject()
								}
							});
						})
					},
					fail: () => {
						reject()
					}
				})
			} catch (e) {
			}

		})
	}

	const getBase64 = (imgUrl : string) : Promise<string> => {
		return new Promise((resolve, reject) => {
			let xhr = new XMLHttpRequest();
			const time = +new Date();
			xhr.open('get', imgUrl + `?time=${time}`, true);
			// 重点1
			xhr.responseType = 'blob';
			xhr.onload = function () {
				if (this.status == 200) {
					//得到一个blob对象
					let blob = this.response;
					// 重点2
					let oFileReader = new FileReader();
					oFileReader.onloadend = function (e) {
						// 结果
						const base64 : string = e.target.result
						resolve(base64);
					};
					oFileReader.readAsDataURL(blob);
				}
			};
			xhr.send();
		})
	}









	function clickBtn() : void {
		selectPosterRef.value.open();
	}
</script>

<style scoped lang="scss">
	@import "./share.scss";
</style>